package cn.hn.java.summer.mvc;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jxls.common.Context;
import org.jxls.util.JxlsHelper;
import org.springframework.web.servlet.view.AbstractView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by xw2sy on 2017-06-27.
 */
public class JxlsExcelView extends AbstractView{
    private Log logger= LogFactory.getLog(getClass());
    //媒体类型
    private static final String CONTENT_TYPE = "application/vnd.ms-excel";
    //模板路径
    private String templatePath;
    public String getTemplatePath() {
        return templatePath;
    }

    public void setTemplatePath(String templatePath) {
        this.templatePath = templatePath;
    }

    public JxlsExcelView(){
        setContentType(CONTENT_TYPE);
    }

    /**
     * @param templatePath   模版相对于当前classpath路径
     */
    public JxlsExcelView(String templatePath) {
        this.templatePath=templatePath;
        setContentType(CONTENT_TYPE);
    }

    @Override
    protected void renderMergedOutputModel(
            Map<String, Object> model,
            HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        //取导出的文件名
        String exportFileName=request.getParameter("fileName");
        if(exportFileName==null){
            exportFileName="export";
        }
        exportFileName= URLDecoder.decode(exportFileName, "UTF-8");
        try {
            exportFileName = URLEncoder.encode(exportFileName, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            exportFileName="export";
            logger.error("encode fileName failed", e);
        }

        //将请求地址作为模板文件名
        String templateFileName=request.getServletPath();
        Context context = new Context(model);
        response.setContentType(getContentType());
        response.setHeader("content-disposition",
                "attachment;filename=\"" + exportFileName + ".xls\"");
        ServletOutputStream os = response.getOutputStream();
        InputStream is =null;
        try {
            is = getClass().getClassLoader().getResourceAsStream(templatePath + templateFileName);
            JxlsHelper.getInstance().processTemplate(is, os, context);
        }finally {
            if(is!=null) {
                is.close();
            }
        }
    }

}